import React, {  useState, useEffect, useRef } from "react"
import {Bars3Icon,XMarkIcon, UserIcon, ChevronDownIcon} from "@heroicons/react/24/solid"
import Logo from "../../assets/image/Badge_of_Guangdong_Ocean_Univercity.svg.png"
import { SelectedPage, UserRole } from "../../shared/types"
import useMediaQuery from "../../hooks/useMediaQuery"
import Link from "./Link"
import ActionButton from "../../shared/ActionButtons"
import { gsap } from "gsap"
import { useNavigate } from "react-router-dom"

type Props = {
  selectedPage: SelectedPage,
  setSelectedPage: (value: SelectedPage) => void,
  isTopOfPage: boolean,
  currentUser?: any,
  onLogout?: () => void
}

const Navbar = ({ selectedPage, setSelectedPage, isTopOfPage, currentUser, onLogout }: Props) => {
  const flexBetween = "flex justify-between items-center"
  const isAboveMediumScreen = useMediaQuery("(min-width:1060px)")
  const [isMenuToggled, setIsMenuToggled] = useState(false)
  const [showUserMenu, setShowUserMenu] = useState(false)
  const navbarBackground = isTopOfPage ? "bg-white" : "bg-primary-100 drop-shadow"
  const navRef = useRef<HTMLElement | null>(null)
  const menuRef = useRef<HTMLDivElement | null>(null)
  const userMenuRef = useRef<HTMLDivElement | null>(null)
  const navigate = useNavigate()

  useEffect(() => {
    if (navRef.current) {
      gsap.from(navRef.current, {
        y: -20,
        opacity: 0,
        duration: 0.4,
        ease: "power2.out",
        onComplete: () => {
          if (navRef.current) {
            gsap.set(navRef.current, { clearProps: "opacity,visibility,transform" })
          }
        },
      })
    }
  }, [])

  useEffect(() => {
    if (!isAboveMediumScreen && menuRef.current) {
      if (isMenuToggled) {
        gsap.fromTo(menuRef.current, { x: 300, autoAlpha: 0 }, { x: 0, autoAlpha: 1, duration: 0.35, ease: "power2.out" })
      } else {
        gsap.to(menuRef.current, { x: 300, autoAlpha: 0, duration: 0.3, ease: "power2.in" })
      }
    }
  }, [isMenuToggled, isAboveMediumScreen])

  // 点击外部关闭用户菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setShowUserMenu(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  const handleUserMenuClick = () => {
    setShowUserMenu(!showUserMenu)
  }

  const getUserRoleText = (role: UserRole) => {
    switch (role) {
      case UserRole.ADMIN:
        return '管理员'
      case UserRole.SUPER_ADMIN:
        return '超级管理员'
      case UserRole.STUDENT:
        return '学生'
      default:
        return '用户'
    }
  }

  const handleLoginClick = () => {
    navigate('/login')
  }

  const handleRegisterClick = () => {
    navigate('/register')
  }

 return <nav ref={navRef}>
    <div 
    className={`${navbarBackground} ${flexBetween} fixed top-0 z-30 w-full text-gray-800`}
    >
      <div className={`${flexBetween} w-full px-4`}>
        
        <div className={`${flexBetween} w-full gap-16`}>
          {/* 左侧Logo */}
          <img src={Logo} alt="logo" className="h-10 w-auto" />
          
          {isAboveMediumScreen?(
            <div className={`${flexBetween} w-full`}>
            <div className={`${flexBetween} gap-8 text-xl`}>
              <Link page="首页" selectedPage={selectedPage} setSelectedPage={setSelectedPage}>
              </Link>
              <Link page="器材申请" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="场地管理" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="赛事申请" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="罚款条例" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="公告中心" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
            </div>
            
            {/* 右侧用户区域 */}
            <div className={`${flexBetween} gap-4`}>
              {currentUser ? (
                <div className="relative" ref={userMenuRef}>
                  <button
                    onClick={handleUserMenuClick}
                    className="flex items-center gap-2 bg-white border border-gray-300 rounded-lg px-3 py-2 hover:bg-gray-50 transition-colors"
                  >
                    <UserIcon className="w-5 h-5 text-gray-600" />
                    <span className="text-sm font-medium text-gray-700">{currentUser.name}</span>
                    <span className="text-xs text-gray-500">({getUserRoleText(currentUser.role)})</span>
                    <ChevronDownIcon className="w-4 h-4 text-gray-400" />
                  </button>
                  
                  {showUserMenu && (
                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border py-1 z-50">
                      <div className="px-4 py-2 border-b border-gray-100">
                        <p className="text-sm font-medium text-gray-900">{currentUser.name}</p>
                        <p className="text-xs text-gray-500">{currentUser.email}</p>
                      </div>
                      
                      {currentUser.role === UserRole.ADMIN || currentUser.role === UserRole.SUPER_ADMIN ? (
                        <>
                          <button
                            onClick={() => {
                              setShowUserMenu(false)
                              navigate('/user-management')
                            }}
                            className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                          >
                            用户管理
                          </button>
                          <button
                            onClick={() => {
                              setShowUserMenu(false)
                              navigate('/announcements')
                            }}
                            className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                          >
                            公告管理
                          </button>
                        </>
                      ) : null}
                      
                      <button
                        onClick={() => {
                          setShowUserMenu(false)
                          navigate('/change-password')
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                      >
                        修改密码
                      </button>
                      
                      <button
                        onClick={() => {
                          setShowUserMenu(false)
                          if (onLogout) onLogout()
                        }}
                        className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50"
                      >
                        退出登录
                      </button>
                    </div>
                  )}
                </div>
              ) : (
                <div className="flex items-center gap-3">
                  <button
                    onClick={handleLoginClick}
                    className="text-gray-700 hover:text-primary transition-colors"
                  >
                    登录
                  </button>
                  <button
                    onClick={handleRegisterClick}
                    className="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-300 transition-colors"
                  >
                    注册
                  </button>
                </div>
              )}
            </div>
          </div>):(
            <button 
            className="rounded-full bg-secondary-500 p-2"
            onClick={()=>setIsMenuToggled(!isMenuToggled)}
            title="打开菜单"
            >
              <Bars3Icon className="h-6 w-6 text-white" />
            </button>
          )}
        </div>

      </div>
    </div>

    {/* 移动端菜单 */}
    {!isAboveMediumScreen && isMenuToggled && (
      <div ref={menuRef} className="fixed right-0 bottom-0 z-40 h-full w-[300px] bg-primary-100 drop-shadow-xl">
        <div className="flex justify-end p-12">
            <button onClick={()=>setIsMenuToggled(!isMenuToggled)}
            title="关闭菜单"
            >
            <XMarkIcon className="h-6 w-6 text-gray-400"></XMarkIcon>
          </button>
        </div>
         {/* 移动端菜单项 */}
         <div className="ml-[33%] flex flex-col gap-10">
              <Link page="首页" selectedPage={selectedPage} setSelectedPage={setSelectedPage}>
              </Link>
              <Link page="器材申请" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="场地管理" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="赛事申请" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="罚款条例" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              <Link page="公告中心" selectedPage={selectedPage} setSelectedPage={setSelectedPage}></Link>
              
              {/* 移动端用户菜单 */}
              <div className="border-t border-gray-300 pt-4">
                {currentUser ? (
                  <>
                    <div className="text-sm text-gray-600 mb-2">
                      {currentUser.name} ({getUserRoleText(currentUser.role)})
                    </div>
                    {currentUser.role === UserRole.ADMIN || currentUser.role === UserRole.SUPER_ADMIN ? (
                      <>
                        <button
                          onClick={() => {
                            setIsMenuToggled(false)
                            navigate('/user-management')
                          }}
                          className="text-left"
                        >
                          用户管理
                        </button>
                        <button
                          onClick={() => {
                            setIsMenuToggled(false)
                            navigate('/announcements')
                          }}
                          className="text-left"
                        >
                          公告管理
                        </button>
                      </>
                    ) : null}
                    <button
                      onClick={() => {
                        setIsMenuToggled(false)
                        navigate('/change-password')
                      }}
                      className="text-left"
                    >
                      修改密码
                    </button>
                    <button
                      onClick={() => {
                        setIsMenuToggled(false)
                        if (onLogout) onLogout()
                      }}
                      className="text-red-600 text-left"
                    >
                      退出登录
                    </button>
                  </>
                ) : (
                  <>
                    <button
                      onClick={() => {
                        setIsMenuToggled(false)
                        navigate('/login')
                      }}
                      className="text-left"
                    >
                      登录
                    </button>
                    <button
                      onClick={() => {
                        setIsMenuToggled(false)
                        navigate('/register')
                      }}
                      className="text-left"
                    >
                      注册
                    </button>
                  </>
                )}
              </div>
            </div>
      </div>
    )}
  </nav>
}

export default Navbar